import React, {useEffect, useState} from 'react';
import { Layout, Menu } from 'antd'
import {
    HomeOutlined,
    UserOutlined,
    KeyOutlined,
    GlobalOutlined,
    CheckCircleOutlined,
    PushpinOutlined,
    UserSwitchOutlined,
    IdcardOutlined,
    LockOutlined,
    FileOutlined,
    FileSyncOutlined,
    FileSearchOutlined
} from '@ant-design/icons'
import { useNavigate,useLocation } from 'react-router-dom'
import axios from "axios";
import {connect} from "react-redux";

const { SubMenu } = Menu
const {  Sider } = Layout

const SideMenu = (props) => {
    const navigate = useNavigate();
    const location = useLocation();
    const [menu,setMenu]=useState([])
    const iconList = {
        '/home':<HomeOutlined />,
        '/user-manage':<UserOutlined />,
        '/right-manage':<KeyOutlined />,
        '/news-manage':<GlobalOutlined />,
        '/audit-manage':<CheckCircleOutlined />,
        '/publish-manage':<PushpinOutlined />,
        '/user-manage/lists':<UserSwitchOutlined />,
        '/right-manage/role/list':<IdcardOutlined />,
        '/right-manage/right/list':<LockOutlined />,
        '/news-manage/add':<FileOutlined />,
        '/news-manage/draft':<FileSyncOutlined />,
        '/news-manage/category':<FileSearchOutlined />
    }
    useEffect(()=>{
        axios.get('/rights?_embed=children').then(res=>{
            setMenu(res.data)
        })
    },[])
    const {role:{rights}}=JSON.parse(localStorage.getItem('token'))
    const checkPagePermisson = (item) => {
        return item.pagepermisson && rights.includes(item.key)
    }
    const renderMenu = (menu) => {
        return menu.map((item)=>{
            if(item.children?.length>0 && checkPagePermisson(item)){
                return <SubMenu key={item.key} icon={iconList[item.key]} title={item.title}>
                    {renderMenu(item.children)}
                </SubMenu>
            }

            return checkPagePermisson(item) && <Menu.Item key={item.key} title={item.title} icon={iconList[item.key]} onClick={()=>{
                navigate(item.key)
            }}>
                {item.title}
            </Menu.Item>
        })
    }
    const selectKeys = [location.pathname]
    const openKeys = ['/'+location.pathname.split('/')[1]]
    return (
        <Sider trigger={null} collapsible  breakpoint="lg" collapsed={props.isCollapsed}>
            <div style={{display:'flex',height:'100%','flexDirection':'column'}}>
                <div className="logo">后台管理系统</div>
                <div style={{flex:1,'overflow':'auto'}}>
                    <Menu theme="dark" mode="inline" selectedKeys={selectKeys} defaultOpenKeys={openKeys}>
                        {renderMenu(menu)}
                    </Menu>
                </div>
            </div>
        </Sider>
    );
}
const mapStateToProps=({CollapsedReducer:{isCollapsed}})=>{
    return {
        isCollapsed
    }
}

export default connect(mapStateToProps)(SideMenu)